﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using System.IO;
using System.Net;
using System.Text;
using DevExpress.Web.ASPxCallback;

namespace TireService.Web.View.SalesView
{
    public partial class VendorPriceList : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            if (Page.IsPostBack != true)
            {

            }

            // Bind tirepricelistupdate data to gridview
            BindTirePriceListUpdateData(db);
            try
            {
                int TirePriceListUpdateId = Convert.ToInt32(gvTirePriceListUpdate.GetRowValues(gvTirePriceListUpdate.FocusedRowIndex, "TirePriceListUpdateId"));
                BindTirePriceListData(db, TirePriceListUpdateId);
            }
            catch (Exception)
            {
                // Nothing - no pricelistupdate selected
            }


            // Change gridview pagesize based on dropdownlist
            gvTirePriceList.SettingsPager.PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);

            // Dispose connection to database
            db.Dispose();
        }

        /// <summary>
        /// Function that bind pricelist updates data to gridview
        /// </summary>
        /// <param name="db">Connection to database</param>
        private void BindTirePriceListUpdateData(TireServiceDB db)
        {
            gvTirePriceListUpdate.DataSource = db.GetTirePriceListUpdates();
            gvTirePriceListUpdate.DataBind();
        }

        /// <summary>
        /// Function that bind price list data to gridview
        /// </summary>
        /// <param name="db">Connection to database</param>
        /// <param name="TirePriceListUpdateId">Id on price update</param>
        private void BindTirePriceListData(TireServiceDB db, int TirePriceListUpdateId)
        {
            // Bind to gridview
            gvTirePriceList.DataSource = db.GetTirePriceLists(TirePriceListUpdateId);
            gvTirePriceList.DataBind();
        }

        private string ImportVendorTirePrice()
        {
            string result;

            using (WebClient client = new WebClient())
            {
                //// Download vendor csv file with tire prices
                //string file = client.DownloadString(@"http://viggolaursen.dk/export/prisfil.asp?debitornr=81613613&password=MOBIL");

                // Get app_data location
                string appdatafolder = Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, "App_Data");

                //// Create the file in app_data
                //using (FileStream fs = File.Create(appdatafolder + "\\VLTirePrice.csv", 1024))
                //{
                //    Byte[] info = new UTF8Encoding(true).GetBytes(file);
                //    // Add some information to the file.
                //    fs.Write(info, 0, info.Length);
                //}

                // Read data from csv file
                var csvData =
                    (from row in File.ReadLines(appdatafolder + "\\VLTirePrice_ny.csv")
                    let columns = row.Split(';')
                    //where row.EndsWith("~")
                    select new
                    {
                        VendorItemNumber = columns[0],
                        Description = columns[1],
                        Description2 = columns[2],
                        Model = columns[3],
                        EANnumber = columns[4],
                        CostPrice = columns[5],
                        ListPrice = columns[6],
                        StockQuantity = columns[11],
                        FlexPrice = columns[12],
                        FlexStockQuantity = columns[13],
                        TireTypeId = columns[17],
                        Size = columns[16],
                        Width = columns[15],
                        Height = columns[14],
                        TireSpeedIndexId = columns[19],
                        TireLoadIndexId = columns[20],
                        NoiseValue = columns[25],
                        RoadGrip = columns[24],
                        FuelEconomy = columns[23],
                        BrandId = columns[18],
                        ImagePath = columns[26]
                    });//.Take(9000);

                // Instantiate datalayer
                TireServiceDB db = new TireServiceDB();

                // Create new TirePriceListUpdate
                TirePriceListUpdate pricelistupdate = new TirePriceListUpdate();
                pricelistupdate.UpdateDate = DateTime.Now;

                db.AddTirePriceListUpdate(pricelistupdate);

                string dataconvert_errorlist = "";

                // 1: Summer, 2: Winther (Viggo Laursen) - 2: Summer, 3: Winther (MBH)
                foreach (var item in csvData.Where(p => p.TireTypeId == "1" | p.TireTypeId == "2"))
                {
                    try
                    {
                        TirePriceList price = new TirePriceList();

                        bool dataconvert_success = true;

                        // Determin tiretype
                        if (item.TireTypeId == "1")
                        {
                            // Summer tires
                            price.TireTypeId = 2;
                        }
                        else
                        {
                            // Winther tires
                            price.TireTypeId = 3;
                        }
                        // TODO: Need to convert speedindex, loadindex, brandid, 


                        price.VendorItemNumber = item.VendorItemNumber;
                        price.Description = item.Description;
                        price.Description2 = item.Description2;
                        price.Model = item.Model;
                        price.EANnumber = item.EANnumber;
                        price.CostPrice = Convert.ToDecimal(item.CostPrice);
                        price.ListPrice = Convert.ToDecimal(item.ListPrice);
                        price.StockQuantity = Convert.ToInt32(item.StockQuantity);
                        price.FlexPrice = Convert.ToDecimal(item.FlexPrice);
                        price.FlexStockQuantity = Convert.ToInt32(item.FlexStockQuantity);
                        //price.TireTypeId = Convert.ToInt32(item.TireTypeId);
                        price.Size = Convert.ToDecimal(item.Size);
                        price.Width = Convert.ToDecimal(item.Width);
                        price.Height = Convert.ToDecimal(item.Height);
                        try
                        {
                            price.TireSpeedIndexId = db.GetTireSpeedIndexId(item.TireSpeedIndexId.Trim());
                        }
                        catch (Exception ex)
                        {
                            dataconvert_success = false;
                        }

                        try
                        {
                            price.TireLoadIndexId = db.GetTireLoadIndexId(item.TireLoadIndexId.Trim());
                        }
                        catch (Exception ex)
                        {
                            dataconvert_success = false;
                        }

                        try
                        {
                            price.BrandId = db.GetTireBrandId(item.BrandId.Trim());
                        }
                        catch (Exception ex)
                        {
                            dataconvert_success = false;
                        }

                        price.NoiseValue = Convert.ToInt32(item.NoiseValue);
                        price.RoadGrip = Convert.ToInt32(item.RoadGrip);
                        price.FuelEconomy = Convert.ToInt32(item.FuelEconomy);

                        if (dataconvert_success)
                        {
                            pricelistupdate.TirePriceLists.Add(price);
                            db.AddTirePriceList(price);
                        }
                        else
                        {
                            // Register error import
                            dataconvert_errorlist += item.VendorItemNumber + "<br>";
                        }

                        price.ImagePath = item.ImagePath;
                    }
                    catch (Exception ex)
                    {

                        // Register error import
                        dataconvert_errorlist += item.VendorItemNumber + "(" + ex.Message + ")<br>";
                    }
                    
                }

                // Commit changes to database
                db.SubmitChanges();

                // Dispose database connection
                db.Dispose();

                result = dataconvert_errorlist;
            }

            return result;
        }

        /// <summary>
        /// Button function for export of gridview
        /// </summary>
        protected void btnExport_Click(object sender, EventArgs e)
        {
            if (ddlExport.Value == "0")
            {
                gvExport.WritePdfToResponse();
            }

            if (ddlExport.Value == "1")
            {
                gvExport.WriteXlsToResponse();
            }

            if (ddlExport.Value == "2")
            {
                gvExport.WriteCsvToResponse();
            }

            if (ddlExport.Value == "3")
            {
                gvExport.WriteRtfToResponse();
            }
        }

        protected void callBackImportVendorPriceList_Callback(object sender, CallbackEventArgs e)
        {
            string result = ImportVendorTirePrice();

            e.Result = result;
        }

        protected void gvTirePriceListUpdate_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            BindTirePriceListUpdateData(db);
        }

        protected void gvTirePriceList_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
        {
            TireServiceDB db = new TireServiceDB();
            try
            {
                int TirePriceListUpdateId = Convert.ToInt32(gvTirePriceListUpdate.GetRowValues(gvTirePriceListUpdate.FocusedRowIndex, "TirePriceListUpdateId"));
                BindTirePriceListData(db, TirePriceListUpdateId);
            }
            catch (Exception)
            {
                // Nothing - no pricelistupdate selected
            }
        }

        /// <summary>
        /// Gridview function that change field data for unbound fields
        /// </summary>
        protected void gvTirePriceList_CustomUnboundColumnData(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewColumnDataEventArgs e)
        {
            // Format UnBoundColumn TireDimensions: Show tire dimensions
            if (e.Column.FieldName == "TireDimensions")
            {
                // Get tiresetstatusid
                object Size = e.GetListSourceFieldValue("Size");
                object Width = e.GetListSourceFieldValue("Width");
                object Height = e.GetListSourceFieldValue("Height");

                // Change field value
                try
                {
                    e.Value = Width.ToString() + " / " + Height.ToString() + " " + Size.ToString();
                }
                catch (Exception)
                {
                    e.Value = "";
                }
            }
        }
    }
}